package com.bkhc.common.service;


import com.bkhc.common.entity.ApiInfo;
import com.bkhc.common.entity.ApiPack;
import com.bkhc.common.repository.ApiInfoRepository;
import com.bkhc.common.repository.ApiPackageRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class ApiInfoService {

    private static final Logger logger = LoggerFactory.getLogger(ApiInfoService.class);

    private Map<String,ApiInfo> apimap = new HashMap<>();

    @Autowired
    private ApiInfoRepository repository;

    @Autowired
    private ApiPackageRepository apiPackageRepository;

    public void initApi(Set<ApiPack> packs){
        logger.info("开始初始化权限");
        repository.deleteAll();
        apiPackageRepository.deleteAll();
        for(ApiPack pack:packs){
            apiPackageRepository.save(pack);
            if(!CollectionUtils.isEmpty(pack.getApis())) {
                repository.saveAll(pack.getApis());
            }
        }
        logger.info("初始化权限完成");

    }
    public List<ApiInfo> getCommonApi(){
        List<ApiInfo> res= repository.findByApiType("1");
        return res;
    }

    public ApiInfo getApiByCode(String code){
        ApiInfo api = apimap.get(code);
        if(api == null){
            api= repository.findByCode(code);
            apimap.put(code,api);
        }
        return api;
    }

}
